package com.ojoin.trade.supplyloan_core.web.task;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.jms.Destination;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import com.ojoin.trade.common.exception.BusinessException;
import com.ojoin.trade.common.utils.CacheUtils;
import com.ojoin.trade.common.utils.CommonUtils;
import com.ojoin.trade.common.utils.EmailSendUtil;
import com.ojoin.trade.common.utils.LogUtils;
import com.ojoin.trade.common.utils.TimeUtils;
import com.ojoin.trade.common.web.quartz.CronExpression;
import com.ojoin.trade.common.web.quartz.TaskGroup;
import com.ojoin.trade.common.web.task.BaseQuartzJob;
import com.ojoin.trade.common_core.web.domain.TbMerchantInfo;
import com.ojoin.trade.common_core.web.domain.TbMerchantuserFinaccount;
import com.ojoin.trade.common_core.web.service.TbMerchantInfoBaseService;
import com.ojoin.trade.common_core.web.service.TbMerchantuserFinaccountService;
import com.ojoin.trade.supplyloan_core.constdef.IPlatformUrlDef;
import com.ojoin.trade.supplyloan_core.utils.GetClassByName;
import com.ojoin.trade.supplyloan_core.web.domain.CatchDataStartMessage;
import com.ojoin.trade.supplyloan_core.web.domain.TbCatchdataStrategy;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlPlatformInfo;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlPlatformUser;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlStatetaskRunresultvo;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlSupplyInventory;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlSupplyPayment;
import com.ojoin.trade.supplyloan_core.web.service.TbCatchdataStrategyService;
import com.ojoin.trade.supplyloan_core.web.service.TbSlPlatformInfoService;
import com.ojoin.trade.supplyloan_core.web.service.TbSlPlatformUserService;
import com.ojoin.trade.supplyloan_core.web.service.TbSlStattaskRunresultService;
import com.ojoin.trade.supplyloan_core.web.service.TbSlSupplyInventoryService;
import com.ojoin.trade.supplyloan_core.web.service.TbSlSupplyPaymentService;
import com.ojoin.trade.supplyloan_core.web.service.catchdata.ISLDataCatchBaseService;
import com.ojoin.trade.supplyloan_core.web.service.impl.QueueSenderServieImpl;

/**
 * 供应链贷数据抓取任务
 */

@Component
public class SLcatchDataTask extends BaseQuartzJob {
	
	@Autowired
	private TbSlPlatformUserService platformUserService;

	@Autowired
	private TbSlPlatformInfoService tbSlPlatformInfoService;

	@Autowired
	private TbSlStattaskRunresultService runResultService;

	@Autowired
	private TbSlSupplyPaymentService paymentService;

	@Autowired
	private TbMerchantInfoBaseService InfoBaseService;

	@Autowired
	private TbSlSupplyInventoryService inventoryService;
	@Autowired
	private TbCatchdataStrategyService catchdataStrategyService;
	@Autowired
	protected TbMerchantuserFinaccountService MerchantuserFinaccountService;
	
	@Autowired
	protected QueueSenderServieImpl queueSenderServie;
	

	@Autowired
	@Qualifier("catchDataTask")
	private Destination catchDataTask;

	/*
	 * // TODO:先按平台树，之后按用户 private final int maxthread =
	 * Integer.parseInt(Config.getProperty( TbSlPlatformInfo.sl_config,
	 * "sl.catchdata.maxthread"));
	 */

	private static final Logger log = LoggerFactory
			.getLogger(SLcatchDataTask.class);

	@CronExpression(cron = "0 0 7,8 ? * *", desc = "拉取数据 每天早上 5:00触发(确保取到最新数据)")
	public void autoExecDataCatch() throws BusinessException {

		LogUtils.info(log, "执行任务平台，抓取数据任务已触发");

		List<TbSlPlatformUser> userList = new ArrayList<TbSlPlatformUser>();

		List<TbSlStatetaskRunresultvo> li = runResultService
				.queryByPlatformAndMerchantUserIDAndDate(null, null,
						TimeUtils.getCurDate(), null);

		Map<Integer, TbSlPlatformUser> map = platformUserService.queryMap(null, "id");
		
		if (!CommonUtils.isEmpty(li)) {
			for (TbSlStatetaskRunresultvo tb : li) {
				if (runResultService.isCatchSucceed(tb)) {
					LogUtils.info(log, tb.getPlatformUName() + "抓取成功，不进行抓取");
				} else {
					TbSlPlatformUser user = map.get(tb
							.getIdOfPlatformUser());
					userList.add(user);
				}
			}
		}
		startCatchData(userList);
	}

	public void startCatchData(List<TbSlPlatformUser> users)
			throws BusinessException {

		if (!CommonUtils.isEmpty(users)) {
			for (TbSlPlatformUser user : users) {
				try {
					startCatchData(user);
				} catch (Exception e) {
					LogUtils.info(log, "user: %s  抓取失败", user.getUsername());
					LogUtils.error(log, e);
				}

			}
		}
	}

	public void removePlatformUserId(int platformUserId) {
		CacheUtils.remove(CacheUtils.SL_CATCHDATA_TASK, platformUserId + "");
	}

	public void removeAll() {
		CacheUtils.clear(CacheUtils.SL_CATCHDATA_TASK);
	}

	public void sendMail(List<TbSlPlatformUser> users) throws BusinessException {
		StringBuffer sb = new StringBuffer();
		sb.append("<html><body><table border=\"1\" cellpadding=\"2\" cellspacing=\"0\">");
		int i = 0;
		sb.append(packTitle(2, "抓取任务已经启动"));
		try {
			if (null != users) {
				for (TbSlPlatformUser user : users) {
					if (!CommonUtils.isEmpty(user)) {
						i++;

						if (!user.getEnableFlag().equals(
								IPlatformUrlDef.Statues.disabled.toString())) {

							ISLDataCatchBaseService service = null;
							service = GetClassByName.getCatchServiceByName(user
									.getPlatformName());

							if (null != service) {

								sb.append(pack(i, user.getUsername()
										+ "---执行抓取任务"));
							} else {
								sb.append(packHasColor(i, user.getUsername()
										+ "---service 为空"));
							}
						} else {

							sb.append(packHasColor(i, user.getUsername()
									+ "---账号冻结不抓取"));
						}

					}

				}
			}

		} catch (Exception e) {
			LogUtils.info(log, "邮件内容生成模块出错");
		} finally {
			sb.append("</table></body></html>");
			log.info(sb.toString());
			try {
				EmailSendUtil.send("296558063@qq.com", "抓取数据任务", sb.toString());
			} catch (Exception e) {
				LogUtils.error(log, e);
			}

		}

	}

	public void startCatchData(TbSlPlatformUser user) throws BusinessException {

		if (!CommonUtils.isEmpty(user)) {

			if (null == CacheUtils.get(CacheUtils.SL_CATCHDATA_TASK, user.getId() + "")) {
				if (!user.getEnableFlag().equals(
						IPlatformUrlDef.Statues.disabled.toString())) {

					CatchDataStartMessage ca = new CatchDataStartMessage();
					TbSlPlatformInfo info = tbSlPlatformInfoService
							.queryByName(user.getPlatformName());
					TbCatchdataStrategy tc = catchdataStrategyService
							.queryByPlatformUserId(user.getId());

					if (null == tc) {
						tc = new TbCatchdataStrategy();
						tc.setPlatformUserId(user.getId());
						catchdataStrategyService.save(tc);
					}

					// 时间生成
					String etime = TimeUtils.getCurDate();

					String storeInstarttime = inventoryService
							.getLastStoreDate(user.getId(),
									TbSlSupplyInventory.IN);
					String storeOutstarttime = inventoryService
							.getLastStoreDate(user.getId(),
									TbSlSupplyInventory.OUT);

					if (info.getPlatformName().equals(
							TbSlPlatformInfo.THIRDSELLER_JD)) {
						String JDstorePayTime = inventoryService
								.getLastStoreDate(user.getId(),
										TbSlSupplyInventory.PAY);
						if (CommonUtils.isEmpty(JDstorePayTime)) {
							if (tc.getIsInit().equals(
									TbCatchdataStrategy.noinit)) {
								JDstorePayTime = etime;
							} else {
								JDstorePayTime = TimeUtils.getDateBefore(2);
							}
						}
						ca.setJDstorePayTime(JDstorePayTime);
					}

					String unpaystarttime = paymentService.getLastcreateDate(
							user.getId(), TbSlSupplyPayment.WAITPAY);
					String paystarttime = paymentService.getLastcreateDate(
							user.getId(), TbSlSupplyPayment.COMPLETEPAY);

					if (CommonUtils.isEmpty(storeInstarttime)) {
						storeInstarttime = TimeUtils.getDateBefore(tc
								.getInventoryInterval());
					} else {
						storeInstarttime = storeInstarttime.replace("/", "-");
					}

					if (CommonUtils.isEmpty(storeOutstarttime)) {
						storeOutstarttime = TimeUtils.getDateBefore(tc
								.getInventoryInterval());
					} else {
						storeOutstarttime = storeOutstarttime.replace("/", "-");
					}

					if (CommonUtils.isEmpty(unpaystarttime)) {
						unpaystarttime = TimeUtils.getDateBefore(tc
								.getSettlementInterval());
					} else {
						unpaystarttime = unpaystarttime.replace("/", "-");
					}
					if (CommonUtils.isEmpty(paystarttime)) {
						paystarttime = TimeUtils.getDateBefore(tc
								.getSettlementInterval());
					} else {
						paystarttime = paystarttime.replace("/", "-");
					}

					// 初始化数据生成
					Map<String, TbSlSupplyInventory> mapin = null;
					Map<String, TbSlSupplyInventory> mapout = null;
					Map<String, TbSlSupplyPayment> waitpay = null;
					Map<String, TbSlSupplyPayment> completepay = null;

					if (tc.getInventoryCatchAllOrPart().equals(
							TbCatchdataStrategy.CatchAll)) {
						mapin = inventoryService
								.queryInventoryInByStoreDateMap(user.getId(),
										etime, etime);
						mapout = mapin;

					} else {
						mapin = inventoryService.queryInventoryMap(
								user.getId(), TbSlSupplyInventory.IN);
						mapout = inventoryService.queryInventoryMap(
								user.getId(), TbSlSupplyInventory.OUT);

					}

					if (tc.getPaymentCatchAllOrPart().equals(
							TbCatchdataStrategy.CatchAll)) {
						waitpay = paymentService.queryByUidAndCreateDateMap(
								user.getId(), etime, etime,
								TbSlSupplyPayment.WAITPAY);

						completepay = paymentService
								.queryByUidAndCreateDateMap(user.getId(),
										etime, etime,
										TbSlSupplyPayment.COMPLETEPAY);

					} else {
						waitpay = paymentService.queryByUidAndsettlementState(
								user.getId(), TbSlSupplyPayment.WAITPAY);
						completepay = paymentService
								.queryByUidAndsettlementState(user.getId(),
										TbSlSupplyPayment.COMPLETEPAY);
					}

					if(!CommonUtils.isEmpty(user.getIdOfFinaceaccount())){
						TbMerchantuserFinaccount tf = MerchantuserFinaccountService.queryById(user.getIdOfFinaceaccount());
						ca.setMerchantuserFinaccount(tf);
					}
					
					ca.setStoreIn(mapin);
					ca.setStoreOut(mapout);
					ca.setWaitpay(waitpay);
					ca.setCompletepay(completepay);

					// 时间设置
					ca.setSettlementStartTime(unpaystarttime);
					ca.setSettlementEndTime(etime);

					ca.setPaymentStartTime(paystarttime);
					ca.setPaymentEndTime(etime);

					ca.setStoreInStartTime(storeInstarttime);
					ca.setStoreInEndTime(etime);

					ca.setStoreOutStartTime(storeOutstarttime);
					ca.setStoreOutEndTime(etime);

					TbMerchantInfo userInfo = InfoBaseService
							.queryInfoByJoinId(user.getIdOfTbMerchantUser());
					ca.setMerchantUser(userInfo);

					ca.setPlatformInfo(info);
					ca.setPlatformUser(user);

					// 防止重复请求出现

					CacheUtils.put(CacheUtils.SL_CATCHDATA_TASK, user.getId() + "", user);

					LogUtils.info(log, "抓取任务已发送  --> id {%s} userName{%s}",
							user.getId(), user.getUsername());

					if (user.getPlatformName().equals(
							TbSlPlatformInfo.SUPPLIER_TMALL)
							|| user.getPlatformName().equals(
									TbSlPlatformInfo.THIRDSELLER_SUNING)
							|| user.getPlatformName().equals(
									TbSlPlatformInfo.SUPPLIER_SUNING)
							|| 	user.getPlatformName().equals(
									TbSlPlatformInfo.THIRDSELLER_TMALL)	) {

						ca.setCatchType(CatchDataStartMessage.LOCALHOST);
					} else if (user.getPlatformName().equals(
							TbSlPlatformInfo.THIRDSELLER_JD)) {
						ca.setCatchType(CatchDataStartMessage.REMOTEHOST);
					}
					queueSenderServie.send(catchDataTask, ca);
				} else {

					LogUtils.info(
							log,
							"platformName->" + user.getPlatformName()
									+ " joinid->"
									+ user.getIdOfTbMerchantUser() + "  id-->"
									+ user.getId() + "  username->"
									+ user.getUsername() + " 账号冻结不抓取");
				}
			} else {

				LogUtils.info(
						log,
						"platformName->" + user.getPlatformName() + " joinid->"
								+ user.getIdOfTbMerchantUser() + "   id-->"
								+ user.getId() + " username->"
								+ user.getUsername() + " 您的更新请求已经提交，请等待处理");

				throw new BusinessException("您的更新请求已经提交，请等待处理");
			}

		}

	}

	public String pack(int num, String str) {
		return "<tr><td>" + num + "</td><td>" + str + "</td></tr>";
	}

	public String packTitle(int num, String str) {
		return "<tr><td colspan =" + num + ">" + str + "</td></tr>";
	}

	String packHasColor(int num, String str) {
		return "<tr style=\"color:red\"><td>" + num + "</td><td>" + str
				+ "</td></tr>";
	}

	@Override
	public TaskGroup getTaskGroupName() {
		return TaskGroup.SYNCDATA;
	}

}
